<template>
  <div class="HotTopicDetail">
    <div
      class="carousel-container"
      @mouseenter="stopAutoPlay"
      @mouseleave="startAutoPlay"
    >
      <div class="carousel-wrapper" ref="carouselWrapper">
        <div
          class="carousel-track"
          :style="{
            transform: `translateX(-${currentPosition}px)`,
            transition: transitionStyle,
          }"
        >
          <div
            class="carousel-item"
            v-for="(item, index) in items"
            :key="index"
          >
            <div
              class="items"
              @click.stop="handleItemClick(item)"
              :title="item.hoteventName"
            >
              <img
                :src="`/api/frontend/file/download/${item.fileId}`"
                class="item-image"
              />
              <div class="tiem-text">
                {{ item.hoteventName }}
              </div>
            </div>
            <div class="indicator1" v-if="activeIndex == item.hoteventId">
              <div class="indicator"></div>
            </div>
          </div>
        </div>
        <div class="prev-btn" @click="prevPage">
          <i class="el-icon-arrow-left"></i>
        </div>
        <div class="next-btn" @click="nextPage">
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
    </div>

    <div class="Introduction">
      <div class="Introduction-title">{{ zi.hoteventName }}</div>
      <div class="Introduction-coce">
        {{ zi.hoteventDescription }}
      </div>
    </div>
    <div class="Content">
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          type="primary"
          :timestamp="activity.releasetime"
          placement="top"
        >
          <div class="content-item">
            <div class="item-header">
              <div class="item-title">{{ activity.title }}</div>
              <div class="item-action">
                <i class="iconfont icon-shoucangliang"></i>
                收藏
              </div>
            </div>
            <div class="item-meta">
              <div class="meta-item">
                时间：<span>{{ activity.createTime }}</span>
              </div>
              <div class="gang">|</div>
              <div class="meta-item">
                来源： <span>{{ activity.tag }}</span>
              </div>
              <div class="gang">|</div>
              <div class="meta-item">
                作者： <span>{{ activity.zuozheList }}</span>
              </div>
            </div>
            <div class="item-ss">
              机构：<span>{{ activity.zuozhedanweiList }}</span>
            </div>
            <div class="item-ss">
              摘要：<span :title="activity.summary">{{
                activity.summary
              }}</span>
            </div>
            <div class="item-ss">
              关键词：<span>{{ activity.keywordList }}</span>
            </div>
            <div class="bt"  v-if="activity.attachmentFlag == 1">
              <el-button
                type="primary"
                icon="iconfont icon-wenjianyulan"
                plain
              
                @click="handleDownload(activity)"
                >在线阅读</el-button
              >
              <el-button
                type="primary"
                icon="iconfont icon-xiazai"
                plain
           
                @click="Download(activity)"
                >下载</el-button
              >
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script>
import service from "@/service/service";

export default {
  name: "HotTopicDetail",
  props: {
    itemWidth: {
      type: Number,
      default: 355,
    },
    loop: {
      type: Boolean,
      default: true,
    },
    autoPlayInterval: {
      type: Number,
      default: 3000,
    },
  },
  data() {
    return {
      items: [],
      currentPage: 1,
      pageSize: 100,
      zi: {},
      currentIndex: 0,
      isTransitioning: false,
      autoPlay: false,
      interval: null,
      activeIndex: 0,
      activities: [
        {
          timestamp: "2018-04-12 20:46",
          type: "primary",
        },
        {
          timestamp: "2018-04-12 20:46",
          type: "primary",
        },
        {
          timestamp: "2018-04-12 20:46",
          type: "primary",
        },
      ],
    };
  },
  computed: {
    currentPosition() {
      return this.currentIndex * this.itemWidth;
    },
    transitionStyle() {
      return this.isTransitioning ? "transform 0.5s ease" : "none";
    },
    hasNextPage() {
      return true;
    },
    hasPrevPage() {
      return true;
    },
  },
  methods: {
    async getHotTopic() {
      try {
        this.loading = true;
        const res = await service({
          url: "/frontend/index/hotEventList",
          method: "post",
          data: {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
          },
        });
        if (res.code === 200) {
          this.items = res.data.list;
          this.items.filter((item) => {
            if (item.hoteventId == this.$route.query.id) {
              this.zi = item;
              this.activeIndex = item.hoteventId;
            }
          });
        } else {
          this.$message.error(res.msg || "数据获取失败");
        }
      } catch (error) {
        console.error("获取热点事件失败:", error);
        this.$message.error("数据获取失败");
      } finally {
        this.loading = false;
      }
    },
    // 热点事件详情-资源列表
    async getHotTopicDetail() {
      try {
        this.loading = true;
        const res = await service({
          url: "/frontend/index/eventResourceList",
          method: "post",
          data: {
            pageNo: 1,
            pageSize: 100,
            hoteventId: this.activeIndex,
          },
        });
        if (res.code === 200) {
          console.log(res, "11111");
          this.activities = res.data.list.map((item) => ({
            ...item,
            zuozheList: Array.isArray(item.zuozheList)
              ? item.zuozheList.join(";")
              : item.zuozheList,
            zuozhedanweiList: Array.isArray(item.zuozhedanweiList)
              ? item.zuozhedanweiList.join(";")
              : item.zuozhedanweiList,
            keywordsList: Array.isArray(item.keywordsList)
              ? item.keywordsList.join(";")
              : item.keywordsList,
            topicMainWordList: item.thetas?.topicMainWordList
              ? Array.isArray(item.thetas.topicMainWordList)
                ? item.thetas.topicMainWordList.join(";")
                : item.thetas.topicMainWordList
              : "",
            language: item.language === "chinese" ? "中文" : "外文",
            featureName: item.feature?.featureName || "",
            tagName: item.resourceTag?.tagName || "",
            country: item.resourceTag?.country || "",
          }));
        } else {
          this.$message.error(res.msg || "数据获取失败");
        }
      } catch (error) {
        console.error("获取热点事件详情失败:", error);
        this.$message.error("数据获取失败");
      }
    },
    //
    async Download(activity) {
      console.log(activity);
      try {
        const res = await service({
          url: `/frontend/file/download/${activity.fileId}`,
          method: "get",
          responseType: "blob",
        });
        if (res instanceof Blob && res.type === "application/json") {
          const text = await res.text();
          const errorData = JSON.parse(text);
          this.$message.error(errorData.msg || "下载失败，请重试");
          return;
        }
        const url = URL.createObjectURL(res);
        const a = document.createElement("a");
        a.href = url;
        // 使用原始文件名
        a.download = activity.filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      } catch (error) {
        console.error("下载失败:", error);
        this.$message.error("下载失败，请重试");
      }
    },
    async handleDownload(row) {
      if (!row.fileId) {
        this.$message.warning("该资源没有可预览的文件");
        return;
      }
      try {
        const res = await service.post("/frontend/file/preview", [row.fileId]);
        if (res.code === 200 && res.data[row.fileId]) {
          // 直接在新窗口打开预览地址
          window.open(res.data[row.fileId], "_blank");
        } else {
          this.$message.error("获取预览地址失败");
        }
      } catch (error) {
        console.error("预览失败:", error);
        this.$message.error("预览失败，请重试");
      }
    },
    handleItemClick(item) {
      this.activeIndex = item.hoteventId;
      this.$router.push({
        path: "/HotTopicDetail",
        query: {
          id: item.hoteventId || item.text,
        },
      });
      this.zi = item;
      this.getHotTopicDetail();
    },
    nextPage() {
      if (this.isTransitioning) return;

      this.isTransitioning = true;
      let nextIndex = this.currentIndex + 4;

      if (nextIndex >= this.items.length) {
        nextIndex = 0;
      }

      this.currentIndex = nextIndex;

      setTimeout(() => {
        this.isTransitioning = false;
        this.startAutoPlay();
      }, 500);
    },
    prevPage() {
      if (this.isTransitioning) return;

      this.isTransitioning = true;
      let prevIndex = this.currentIndex - 4;

      if (prevIndex < 0) {
        prevIndex = Math.max(0, this.items.length - 4);
      }

      this.currentIndex = prevIndex;

      setTimeout(() => {
        this.isTransitioning = false;
        this.startAutoPlay();
      }, 500);
    },
    startAutoPlay() {
      if (this.autoPlay && !this.isTransitioning) {
        this.stopAutoPlay();
        this.interval = setInterval(() => {
          this.nextPage();
        }, this.autoPlayInterval);
      }
    },
    stopAutoPlay() {
      if (this.interval) {
        clearInterval(this.interval);
        this.interval = null;
      }
    },
  },
  mounted() {
    this.getHotTopic();

    if (this.items.length < 4) {
      this.currentIndex = 0;
    }
    console.log(this.$route.query.id, "111");
    this.activeIndex = this.$route.query.id;
    this.startAutoPlay();
    this.getHotTopicDetail();
  },
  beforeDestroy() {
    this.stopAutoPlay();
  },
};
</script>

<style scoped lang="scss">
.Content {
  padding: 34px 20px;
  width: 1360px;
  margin-bottom: 40px;
  background: #ffffff;

  .content-item {
    margin-top: 24px;
    margin-left: -9px;
    width: 1288px;
    background: #ffffff;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding: 24px;

    .item-header {
      display: flex;
      justify-content: space-between;
      cursor: pointer;

      .item-title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 22px;
        color: #333333;
        line-height: 30px;
      }

      .item-action {
        i {
          font-size: 18px;
          color: #999999;
        }

        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 18px;
        color: #666666;
      }
    }

    .item-meta {
      display: flex;
      align-items: center;
      margin-top: 20px;

      .meta-item {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 18px;
        color: #333333;

        span {
          font-size: 18px;
          color: #666666;
        }
      }

      .gang {
        padding: 0 20px;
      }
    }

    .item-ss {
      margin-top: 16px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #333333;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;

      span {
        color: #666666;
      }
    }

    .bt {
      margin-top: 31px;
      border-top: 1px solid #e4e4e4;
      padding: 20px 0;
    }
  }
}

::v-deep .el-timeline-item__wrapper {
  padding-left: 33px;
}

::v-deep .el-timeline-item__timestamp {
  height: 32px;
  background: #327dff;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 18px;
  color: #ffffff;
  padding: 0 7px;
  display: inline-block;
  line-height: 30px;
  text-align: center;
  border-radius: 4px;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    left: -10px;
    top: 50%;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 5px 10px 5px 2px;
    border-color: transparent #327dff transparent transparent;
  }
}

::v-deep .el-timeline-item__node--normal {
  left: -9px;
  width: 28px;
  height: 28px;
  background: rgba(50, 125, 255, 0.4);

  &::before {
    content: "";
    position: absolute;
    width: 20px;
    height: 20px;
    background: #327dff;
    top: 50%;
    left: 50%;
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }
}

.Introduction-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 24px;
  color: #333333;
}

.Introduction-coce {
  margin-top: 13px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 18px;
  color: #666666;
  line-height: 32px;
}

.Introduction {
  margin-top: 9px;
  margin-bottom: 20px;
  padding: 30px;
  width: 1340px;
  min-height: 202px;
  background: #ffffff;
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.07);
  border-radius: 4px;
}

.indicator1 {
  height: 20px;
}

.indicator {
  width: 335px;
  height: 6px;
  background: #327dff;
  border-radius: 2px;
  margin-top: 7px;
  position: relative;
}

.indicator::before {
  content: "";
  position: absolute;
  width: 15px;
  height: 7px;
  bottom: -10px;
  left: 50%;
  margin-left: -7.5px;
  background: url(../assets/img/detRecommend_icon.png) no-repeat;
  transform: rotate(180deg);
}

.HotTopicDetail {
  padding-top: 24px;
  display: flex;
  background: #f9faff;
  flex-direction: column;
  align-items: center;
}

.items {
  position: relative;
  height: 180px;
  width: 335px;
  flex-shrink: 0;
  box-sizing: border-box;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 10px;
}

.tiem-text {
  font-family: DingTalk, DingTalk;
  font-weight: normal;
  font-size: 36px;
  color: #ffffff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
  padding: 0 10px;
  box-sizing: border-box;
}

.carousel-container {
  position: relative;
  width: 1400px;
  margin: 0 auto;
  overflow: hidden;
}

.carousel-wrapper {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.carousel-track {
  display: flex;
  flex-direction: row;
  width: auto;
  position: relative;
}

.carousel-item {
  margin-right: 20px;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.prev-btn,
.next-btn {
  width: 24px;
  height: 40px;
  background: #ffffff;
  border-radius: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0.6;
  transition: background-color 0.3s ease;
  position: absolute;
  top: 45%;
  transform: translateY(-50%);
  z-index: 1;
}

.prev-btn {
  left: 10px;
}

.next-btn {
  right: 10px;
}

.prev-btn:hover,
.next-btn:hover {
  background-color: #359e75;
}
</style>
